import request from "@/utils/request";
import FP from 'fingerprintjs2'

let getDeviceString = (components)=>{
    const values = components.filter(d=>{
        return d.key === "userAgent" || d.key === "cpuClass" || d.key === "platform"
            || d.key === "canvas" || d.key === "webgl" || d.key === "webglVendorAndRenderer";
    }).map(function(component,index) {
        if (index === 0) { //把微信浏览器里UA的wifi或4G等网络替换成空,不然切换网络会ID不一样
            return component.value.replace(/\bNetType\/\w+\b/, '')
        }
        return component.value;
    })
    return values.join('');
}

let getDeviceId = ()=>{
    // let deviceInfo = getDeviceInfo(navigator.userAgent);
    return new Promise((resolve) => {
        FP.get((components)=>{
            try{
                let deviceString = getDeviceString(components);
                resolve(FP.x64hash128(deviceString, 31));
            }catch (e){
                resolve("");
            }
        });
    });
}

export function login(loginUser){
    return new Promise((resolve, reject) => {
        getDeviceId().then(value => {
            request({
                url:"/auth/oauth/token",
                headers:{"Content-Type":"application/x-www-form-urlencoded","unique-device":value},
                transformRequest: [function (data) {
                    let ret = ''
                    for (let it in data) {
                        ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
                    }
                    return ret
                }],
                method:"post",
                data:Object.assign({grant_type:'password',client_id:"yingcode",client_secret:"yingcode",deviceId:value},loginUser),
                withCredentials: true
            }).then(value => resolve(value)).catch(reason => reject(reason));
        })
    })
}

export function logout(){
    return request({
        url:"/auth/logout",
        method:"get"
    })
}

export function getCaptcha(){
    return  new Promise((resolve, reject) => {
        getDeviceId().then(value => {
            request({
                url:"/auth/captcha/character",
                headers: {"unique-device":value},
                method:"get"
            }).then(resolve)
            .catch(reject);
        })
    })

}